package com.wooboo.server.ext.action.phone.traffic;

import java.util.SortedMap;
import java.util.TreeMap;


import com.alibaba.fastjson.JSONObject;
import com.wooboo.server.ext.ActionBase;
import com.wooboo.server.ext.ApiError;
import com.wooboo.server.ext.Config;
import com.wooboo.server.ext.Logger;
import com.wooboo.server.ext.Result;
import com.wooboo.server.ext.data.PhoneTrafficGift;
import com.wooboo.server.ext.data.Traffic;
import com.wooboo.server.ext.data.UserFinance;
import com.wooboo.server.ext.service.DbService;
import com.wooboo.server.ext.service.PushService;
import com.wooboo.server.ext.util.Des3;
import com.wooboo.server.ext.util.HttpClientUtils;
import com.wooboo.server.ext.util.Parameters;
import com.wooboo.server.ext.util.StringUtil;

/**
 * @author www.wooboo.com.cn
 * 流量汇企业信息注册申请
 */
public class Notify extends ActionBase{

	
	public static final Logger logger = Logger.getLogger("notify");
	
	public String portalType,portalID,transactionID,method,sequence,company_code;
	
	public String msisdn;//手机号
	public String product_id;//电话
	public String oper_time;//邮件
	public String result;
	public String resultDesc;
	public String sign;
	
	SortedMap<String, String> map =  new TreeMap<String, String>();
	
	public Notify(){
		 needCheckAuth =false;
	}
	
	@Override
	public void initParameters(Parameters params) throws ApiError {
		map.put("portalType",params.getFieldValue("portalType")); 
		map.put("portalID",params.getFieldValue("portalID")); 
		map.put("transactionID",params.getFieldValue("transactionID")); 
		map.put("method",params.getFieldValue("method")); 
		map.put("sequence",params.getFieldValue("sequence")); 
		map.put("company_code",params.getFieldValue("company_code")); 
		map.put("msisdn",params.getFieldValue("msisdn")); 
		map.put("product_id",params.getFieldValue("product_id")); 
		map.put("oper_time",params.getFieldValue("oper_time")); 
		map.put("result",params.getFieldValue("result")); 
		map.put("resultDesc",params.getFieldValue("resultDesc")); 
		String sign = params.getFieldValue("sign");
		boolean b = Traffic.verify(map, sign);
		if(!b){
			throw ApiError.Type.INVALID_PARAM.toException("签名错误！");
		}
		
	}
	
	@Override
	public Result invokeService() throws ApiError {
		Result result = new Result();
		JSONObject data = new JSONObject();
		DbService dbService = new DbService();
		String resultData = map.get("result");
		PhoneTrafficGift tg = dbService.findPhoneTrafficGiftBySequence(map.get("sequence"));
		if("0".equals(resultData)){
			if(null!=tg){
				 dbService.update4PhoneTrafficGiftSuccess(tg);
				 UserFinance uf = dbService.findUserFinanceById(tg.getAdvertiser_id());
			     if(uf.getTraffic_yuan()<=0){
			    	 PushService pushService = new PushService();
			    	 pushService.openClose(StringUtil.dealNull(tg.plan_id), PushService.Action.plan_close.toString());
			     }
			     
			     HttpClientUtils.readFromURL(getTrafficUrl("traffic.url", tg), "utf-8");
			     
			}
		}else{
			dbService.update4PhoneTrafficGiftFail(tg);
		}
		logger.logInfo(logstr(tg.sequence,tg.phone_number,tg.advertiser_id,tg.price,resultData));
		data.put("message", "ok");
		data.put("status", "ok");
		data.put("code", "0");
		result.setResponseString(data.toString());
	    return result;
	}
	

	public  String getTrafficUrl(String key,PhoneTrafficGift tg ){
			String url = Config.getValue(key);
			
			JSONObject o = new JSONObject();
			o.put("request_id",StringUtil.createId(12));
			o.put("user_id", map.get("msisdn"));
			o.put("plan_id", tg.plan_id);
			o.put("group_id", tg.group_id);
			o.put("idea_id", tg.iead_id);
	        o.put("billing_type","");
	        o.put("traffic", tg.getProduct_value());
	        o.put("price", tg.getPrice());
			o.put("timestamp", System.currentTimeMillis());
	        try {
				String params = Des3.encode(o.toJSONString());
				return url+"?p="+StringUtil.encode(params, "utf-8");
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
	}
	
	private  String logstr(Object ...strs) {
		StringBuffer sb = new StringBuffer();
			for (Object str:strs) {
				sb.append(StringUtil.dealNull(str));
				sb.append("\t");
			}
	    return sb.toString();
	}

}
